package com.mfrs;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * user:cily
 * time:2017/8/17
 * desc:
 */

public class HttpU {

    public static void load(final String urlStr, final Handler handler){
        new Thread(){
            @Override
            public void run() {
                HttpURLConnection conn = null;
                try {
                    URL url = new URL(urlStr);
                    conn = (HttpURLConnection) url.openConnection();

                    conn.setConnectTimeout(5 * 1000);//设置网络连接超时
                    conn.setReadTimeout(10 * 1000);//设置读取数据超时
                    conn.setDoInput(true);//设置是否从httpUrlConnection读入，默认情况下是true;
            /*
             *设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在
             *http正文内，因此需要设为true, 默认情况下是false;
             */
                    //conn.setDoOutput(true);

                    InputStream in = conn.getInputStream();
                    Bitmap bm = BitmapFactory.decodeStream(in);

            /* 1、android子线程不能更新主线程创建的组件解决方法
             *
             * 2、如果强制使用 imageview.setImageBitmap(bitmap);
             *   则会报错 android.view.ViewRootImpl$CalledFromWrongThreadException
             */
                    Message message = Message.obtain();
                    message.obj = bm;
                    handler.sendMessage(message);

                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally {
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }.start();
    }
}
